import React, { Component } from 'react';
import { Modal, Upload, message, Button, Icon, DatePicker, TimePicker, Spin, Radio, Select } from 'antd';
import './scss/CreateNotice.scss';
import './scss/NewsList.scss';
import { getData, postData, GUID, delData, putData, getQueryVariable } from '../../common/js/fetch';
import Base64 from '../../common/js/fetch/base64';
import { Scrollbars } from 'react-custom-scrollbars';
import Alert from '../../common/compont/alert_dialog_wrapper';
import ClassCropperModal from "../../common/CropperModal";
import $ from 'jquery';
import MyEditor from './MyEditor';
import {SKIN_BG_COLOR} from '../../hooks/useGetThem'
import { LgButton, LgInput, LgSelect, LgPopLayer, LgDrawer, lgAlert } from 'lancoo-web-ui';

const { Option } = Select
const format = 'HH:mm';
const BYTES_PER_SLICE = 1024 * 1024;
window.jquery = $;

class CreateNotice extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            noticeTitle: '',
            fileList: [],
            id: '',
            isupload: false,
            serverTime: '',
            TemplateList: [],
            NoticeContent: '',
            NoticeMain: 0,
            visible4: false,
            NewsID: '',
            loading: false,
            addTypeBtn: true,
            ImportClick: false,
            Newstype: { newsTypeName: '' },
            NewsTypeList: [],
            NewsTypeListIDx: 0,
            message: '是否要删除该类别？',
            isOpen: false,
            NewsTitleImg: '',
            classResultImgUrl: '',
            picVisible: false,
            pushFlag: false,
            aspectRatio: 140 / 95,
            editorContent: '',
            typeId: undefined,
            typeVisible: false,
            typeList: [],
            addType: false,
            addTypeTitle: '',
            editTypeTitle: '',
            typeName: '',
            isEdit: false,
            alertInfo: {},
            delete1: false,
            clear: false,
            userId: sessionStorage.getItem('UserID'),
            userName: sessionStorage.getItem('UserName'),
            schoolId: sessionStorage.getItem('schoolId'),
            schoolName: sessionStorage.getItem('schoolName'),
            newsAttachmentVoList: [],
            imgUrl: '',
            imgList: [],
            imgCount: 0,
            fileCount: 0,
            preTypeTitle: '',
            selectValue: '',
            systemInfo: JSON.parse(sessionStorage.getItem('systemInfo')),
            previewSystem: JSON.parse(sessionStorage.getItem('preview')),
        };
        this.createNotice = this.createNotice.bind(this);
        this.clooseType = this.clooseType.bind(this);
        this.formDataRemind = this.formDataRemind.bind(this);
        this.handleGetResultImgUrl = this.handleGetResultImgUrl.bind(this);
        this.CropperModalClose = this.CropperModalClose.bind(this);
        this.hideModal = this.hideModal.bind(this);
        // this.state.newsAttachmentVoList = this.state.newsAttachmentVoList.bind(this);


    }

    option1Click = () => {
        if (this.state.option1 !== 'notice-create-choose') {
            this.setState({
                option1: 'notice-create-choose',
                option2: 'notice-create-unchoose',
                EffectType: 1,
            });
        }

    }

    option2Click = () => {
        if (this.state.option2 !== 'notice-create-choose') {
            this.setState({
                option2: 'notice-create-choose',
                option1: 'notice-create-unchoose',
                EffectType: 2,

            });
        }

    }
    changeNoticeTitle(e) {
        this.setState({
            noticeTitle: e.target.value
        })
    }

    componentWillMount() {
        this.getTypeList();
    }

    componentDidMount() {
        this.getTypeList();
    }

    // componentWillReceiveProps(nextProps) {
    // }

    uploadFile(uploadType, index, fileName, file, fileType, json, guid) {
        let $this = this;
        // console.log(index, fileName, file, fileType, guid);
        console.log(file, 'file');
        if (!guid) {
            guid = new GUID().newGUID();
        }
        let formData = new FormData();
        formData.append('files', file);
        formData.append('modelName', 'newsInfo');

        let fileList = this.state.newsAttachmentVoList.concat([]);

        let type = '';
        if (fileType == 'mp4') {
            type = 'video/mp4';
        } else if (fileType == 'mp3') {
            type = 'audio/mp3';
        } else if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].indexOf(fileType) != -1) {
            type = 'image/' + fileType;
        } else {
            type = fileType;
        }

        $.ajax({
            url: sessionStorage.getItem('itemUrl') + 'api/commons/file/batch/upload',
            type: 'POST',
            cache: false,
            data: formData,
            //dataType: 'json',
            //async: false,
            processData: false,
            contentType: false,
            headers: {
                'Authorization': getQueryVariable('lg_tk') || sessionStorage.getItem('token'),
                'X-Requested-With': 'XMLHttpRequest'
            }
        }).done(function (res) {
            // console.log($this.state.hasSendNum);
            $this.setState({
                hasSendNum: $this.state.hasSendNum
            }, () => {
                console.log('index', index);

                if (uploadType) {
                    $this.setState({
                        NewsTitleImg: diskName + '/' + guid + file.name.slice(file.name.lastIndexOf('.'), file.name.length),
                    })
                } else {
                    console.log(res, 'res');
                    $this.setState({
                        isupload: false,
                    })
                    // message.success('上传成功~');
                    let fileArr = res.data;
                    let files = fileArr.map(item => {
                        return {
                            attachmentUrl: item['url'],
                            attachmentName: item['fileName'],
                            attachmentSize: item['size']
                        }

                    })
                    fileList = fileList.concat(files)
                    if (fileList.length > 1) {
                        $this.setState({
                            pushFlag: false
                        })
                    }
                    $this.setState({
                        newsAttachmentVoList: fileList,
                        isupload: false,
                    }, () => { })
                    message.success('上传附件成功~');
                }

            })
        }).fail(function (res) {
            if (uploadType) {
                $this.setState({
                    NewsTitleImg: '',
                })
            } else {
                $this.setState({
                    isupload: false,
                })
                message.error('上传失败~');
            }

        });
    }
    formDataRemind(e, type) {
        console.log(e, '<====e', type);
        let $this = this;
        let file = '';
        let uploadType = [];
        let imgCounts = this.state.imgCount;
        let fileCounts = this.state.fileCount;
        if (type) {
            file = $('#file1')[0].files[0];
            console.log(file, 'file1111');
            if (file && file.name && file.name.length > 50) {
                message.warn('所上传文件名称不能超过50字符！');
                return;
            }
            if (!file) {
                $this.setState({
                    NewsTitleImg: '',
                })
                $('#file1').val('');
                return;
            }
            if (file.size > 1024 * 10240) {
                message.error('上传附件不能大于10MB~');
                $this.setState({
                    NewsTitleImg: '',
                })
                $('#file1').val('');
                return;
            }
            uploadType = ['jpg', 'jpeg', 'png'];
            if (uploadType.indexOf(file.name.slice(file.name.lastIndexOf('.') + 1, file.name.length)) === -1) {
                message.error('上传文件格式不正确~');
                $this.setState({
                    NewsTitleImg: '',
                })
                $('#file1').val('');
                return;
            }
        } else {
            file = $('#file')[0].files[0];
            console.log(file, 'file123');
            if (file && file.name && file.name.length > 50) {
                message.warn('所上传文件名称不能超过50字符！');
                return;
            }
            if (!file) {
                $this.setState({

                })
                $('#file').val('');
                return;
            }
            if (file.size > 1024 * 10240) {
                message.error('上传附件不能大于10MB~');
                $this.setState({

                })
                $('#file').val('');
                return;
            }
            let uploadType = ['jpg', 'jpeg', 'png', 'bmp', 'mp3', 'mp4', 'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'cab', 'iso', 'mp4', 'mp3', 'txt', 'doc', 'docx', 'docs', 'xls', 'xlsx', 'ppt', 'pdf'];
            let fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
            if (uploadType.indexOf(fileExtension) === -1) {
                message.error('不支持当前文件格式~');
                // 重置上传框的值
                $('#file').val('');
                return;
            }
            $this.setState({
                isupload: 'true',
            })
            //限制文件数量
            let imgType = ['jpg', 'jpeg', 'png', 'bmp', 'gif'];

            if (imgType.indexOf(file.name.slice(file.name.lastIndexOf('.') + 1, file.name.length)) > -1) {
                imgCounts = ++imgCounts;
                if (imgCounts > 4) {
                    message.warn('图片类型附件只能上传四个！');
                    this.setState({
                        isupload: false,
                    })
                    return;
                }
            } else {
                fileCounts = ++fileCounts;
                if (fileCounts > 4) {
                    message.warn('文件类型附件只能上传四个！');
                    this.setState({
                        isupload: false,
                    })
                    return;
                }
            }
            this.setState({
                imgCount: imgCounts,
                fileCount: fileCounts,
            })
        }
        let guid = new GUID().newGUID();
        this.setState({
            totalSize: file.size,
            fileName: file.name,
            hasSendNum: 0,
            totalSlices: Math.ceil(file.size / 1024 / 1024),

        }, () => { this.uploadFile(type, this.state.hasSendNum + 1, this.state.fileName, file, file.name.slice(file.name.lastIndexOf('.') + 1, file.name.length), guid); })

    }
    uploadDel(index, item) {
        let $this = this;
        let {
            imgCount,
            fileCount,
        } = $this.state
        let imgType = ['jpg', 'jpeg', 'png', 'bmp', 'gif'];
        if (imgType.indexOf(item.attachmentName.slice(item.attachmentName.lastIndexOf('.') + 1, item.attachmentName.length)) > -1) {
            imgCount = imgCount - 1;
        } else {
            fileCount = fileCount - 1
        }
        let fileArr = $this.state.newsAttachmentVoList.concat([]);
        fileArr.splice(index, 1);
        $this.setState({
            newsAttachmentVoList: fileArr,
            isupload: false,
            imgCount,
            fileCount,
        })
    }
    createNotice() {
        let {
            noticeTitle,
            editorContent,
            typeId,
            NewsTitleImg,
            userId,
            userName,
            schoolId,
            schoolName,
            NewsID,
            newsId,
            imgUrl,
            newsAttachmentVoList,
            pushFlag,
        } = this.state
        var $this = this;
        console.log($this.state, '$this ');
        if (this.state.noticeTitle.length == 0 || this.state.noticeTitle.trim().length == 0) {
            message.error('新闻标题不能为空~');
            let count = 0;
            let timer = setInterval(() => {
                count++;
                setTimeout(() => {
                    if (count === 3) {
                        clearInterval(timer);
                    }

                    $('.notice-create-title').focus();
                }, 200);
                $('.notice-create-title').blur();
            }, 400);
            return;
        }
        // if (this.state.Newstype.newsTypeName.length == 0 || this.state.Newstype.newsTypeName.trim().length == 0) {
        if (this.state.typeId == '' || this.state.typeId == undefined) {
            message.error('新闻类型不能为空~');
            let count = 0;
            let timer = setInterval(() => {
                count++;
                setTimeout(() => {
                    if (count === 3) {
                        clearInterval(timer);
                        $('.div-select').css('border', 'solid 1px #bac7d9');
                        return;
                    }
                    $('.div-select').css('border', 'solid 2px #bac7d9');
                }, 200);
                $('.div-select').css('border', 'solid 2px #1890ff');

            }, 400);
            return;
        }
        if (this.state.editorContent && this.state.editorContent !== '<p><br></p>') {
            console.log('12121', this.state.editorContent);
        } else {
            message.error('新闻内容不能为空');
            return
        }
        postData('api/news/create/release', {
            // UserID: sessionStorage.getItem('UserID'),
            newsId: NewsID ? NewsID : newsId,
            newsTitle: noticeTitle,
            newsContent: editorContent,
            newsCoverPath: imgUrl,
            userId: userId,
            userName: userName,
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            eduName: schoolName,
            newsTypeId: typeId,
            newsAttachmentVoList: newsAttachmentVoList,
            bePushEdu: pushFlag ? '1' : '0'
        }).then((res) => {
            return res.json();
        }).then((json) => {

            if (json.code == 200) {
                $this.hideModal();
                message.success('发布新闻成功~', 3);
                $this.setState({
                    NoticeMain: 0,
                    editorContent: '',
                    clear: true,
                    typeId: undefined,
                    imgUrl: '',
                    newsAttachmentVoList: []
                }, () => { this.setState({ clear: false, typeId: undefined, imgUrl: '', newsAttachmentVoList: [] }) })
                this.props.reloadType();
                setTimeout(() => {
                    this.props.changeNoticeList(1);
                }, 300);
                $('#file').val('');
            } else {
                message.error(json.msg, 3);
            }
        })
    }
    getTypeList() {
        //获取类型
        getData('api/news/type/list', {
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
        }).then((res) => {
            return res.json()
        }).then((json) => {
            if (json.code == 200 && json.data) {
                let data = json.data.concat([]);
                data.forEach(item => {
                    item.text = item.newTypeName;
                });
                data.push({ newsTypeId: '', text: '类型管理' });
                console.log(json.data, 'json.data');
                this.setState({
                    NewsTypeList: data,
                    typeList: json.data
                })
            } else {
                message.error(json.Msg, 3);
            }
        })
    }
    chooseType(type) {
        this.setState({
            Newstype: type,
            isMouseOut: false,
            isMouseOut1: false,
        }, () => {
            // this.getQuelist('');
        })
    }

    // 如果条件不存在必须要返回null   
    static getDerivedStateFromProps(props, current_state) {
        if (props.NoticeMain !== 0 && current_state.NoticeMain !== 1) {
            if (!props.NoticeMain.NewsCoverPath) {
                props.NoticeMain.NewsCoverPath = '';
            }
            //限制文件数量
            let imgType = ['jpg', 'jpeg', 'png', 'bmp', 'gif'];
            let imgCounts = 0, fileCounts = 0;
            if (props.NoticeMain.newsAttachmentVoList && props.NoticeMain.newsAttachmentVoList.length > 0) {
                props.NoticeMain.newsAttachmentVoList.forEach(item => {
                    if (imgType.indexOf(item.attachmentName.slice(item.attachmentName.lastIndexOf('.') + 1, item.attachmentName.length)) > -1) {
                        imgCounts = ++imgCounts;
                    } else {
                        fileCounts = ++fileCounts;
                    }
                })
            }
            return {
                NewsID: props.NoticeMain.newsId,
                NoticeMain: 1,
                noticeTitle: props.NoticeMain.newsTitle,
                newsAttachmentVoList: props.NoticeMain.newsAttachmentVoList,
                NoticeContent: props.NoticeMain.newsContent,
                editorContent: props.NoticeMain.newsContent,
                newsTypeName: props.NoticeMain.newsTypeName,
                selectValue: props.NoticeMain.newsTypeName,
                typeId: props.NoticeMain.newsTypeId,
                NewsTitleImg: props.NoticeMain.NewsCoverPath,
                // editorContent: props.NoticeMain.newsContent
                clear: false,
                imgUrl: props.NoticeMain.newsCoverPath,
                pushFlag: props.NoticeMain.bePushEdu == '1' ? true : false,
                imgCount: imgCounts,
                fileCount: fileCounts,
            }
        }
        if (props.NoticeMain === 0 && current_state.NoticeMain !== 2) {
            // let timer = setInterval(function () {
            //     if ($('#editor').length > 0) {
            //         // console.log( NoticeContent);
            //         // sessionStorage.setItem('editor', 'editor');
            //         // let ue = window.UE.getEditor('editor');
            //         // ue.setContent('');
            //         clearInterval(timer);
            //     }
            // }, 100)
            return {
                NewsID: '',
                NoticeMain: 2,
                noticeTitle: '',
                NoticeContent: '',
                Newstype: { newsTypeName: '', UserTypeStr: '' },
                NewsTitleImg: '',

            }
        }
        return null
    }
    onoK4() {
        if (this.state.noticeTitle.length == 0 || this.state.noticeTitle.trim().length == 0) {
            message.error('新闻标题不能为空~');
            let count = 0;
            let timer = setInterval(() => {
                count++;
                setTimeout(() => {
                    if (count === 3) {
                        clearInterval(timer);
                    }

                    $('.notice-create-title').focus();
                }, 200);
                $('.notice-create-title').blur();
            }, 400);
            return;
        }
        if (this.state.typeId == '' || this.state.typeId == undefined) {
            message.error('新闻类型不能为空~');
            let count = 0;
            let timer = setInterval(() => {
                count++;
                setTimeout(() => {
                    if (count === 3) {
                        clearInterval(timer);
                        $('.div-select').css('border', 'solid 1px #bac7d9');
                        return;
                    }
                    $('.div-select').css('border', 'solid 2px #bac7d9');
                }, 200);
                $('.div-select').css('border', 'solid 2px #1890ff');
            }, 400);
            return;
        }
        if (this.state.editorContent && this.state.editorContent !== '<p><br></p>') {
            let myDate = new Date();
            let year = myDate.getFullYear();    //获取完整的年份(4位,1970-????)
            let Month = myDate.getMonth() * 1 + 1;       //获取当前月份(0-11,0代表1月)
            let Date1 = myDate.getDate();
            let Hours = myDate.getHours();       //获取当前小时数(0-23)
            if (Hours < 10) {
                Hours = '0' + Hours;
            }
            let Minutes = myDate.getMinutes();

            if (Minutes < 10) {
                Minutes = '0' + Minutes;
            }
            console.log(Hours, Minutes);
            this.setState({
                visible4: true,
                serverTime: year + '-' + Month + '-' + Date1 + ' ' + Hours + ':' + Minutes
            })
        } else {
            message.error('新闻内容不能为空');
        }
    }
    handleCancel4 = () => {
        this.setState({
            visible4: false
        })
    }
    handleCancel3 = () => {
        this.setState({
            visible3: false,
            isMouseOut2: false,
            addTypeBtn: true
        })
    }

    clooseType(e, idx) {
        e.stopPropagation();

        this.setState({
            NewsTypeListIDx: idx,
            isOpen: true,
            isMouseOut2: true,
        })
    }
    showInput = (e) => {
        e.stopPropagation();
        this.setState({
            visible3: true,
            isMouseOut: true,
            isMouseOut2: true,
            isMouseOut1: true,
            addTypeBtn: false
        })
    }

    DeleTypeFn(data) {
        if (data) {
            getData('publicinfo/News/CreateNews/DeleteNewsType', {
                UserType: sessionStorage.getItem('UserType'),
                UserID: sessionStorage.getItem('UserID'),
                NewsTypeID: this.state.NewsTypeList[this.state.NewsTypeListIDx].newsTypeID
            }).then((res) => {
                return res.json()
            }).then((json) => {
                // console.log(json);
                // hide();
                if (json.StatusCode == 200) {
                    let NewsTypeList = this.state.NewsTypeList;
                    if (this.state.NewsTypeList[this.state.NewsTypeListIDx].newsTypeID == this.state.Newstype.newsTypeID) {

                        this.setState({
                            Newstype: { newsTypeName: '', UserTypeStr: '' },
                        })
                    }
                    NewsTypeList.splice(this.state.NewsTypeListIDx, 1);
                    this.setState({
                        NewsTypeList: NewsTypeList,
                        isMouseOut: true,
                        isOpen: false,
                    })
                } else {
                    message.error(json.Msg, 3);
                }
            })
        } else {
            this.setState({
                isOpen: false,
            })
        }

    }
    handleGetResultImgUrl(imgUrl) {
        console.log(imgUrl, 'file');
        this.setState({
            picVisible: false,
            imgUrl: imgUrl
        })
    }
    CropperModalClose(NewsTitleImg) {
        console.log(NewsTitleImg, 'NewsTitleImg');
        if (typeof NewsTitleImg == 'string') {
            this.setState({
                NewsTitleImg: NewsTitleImg,

            })
        }
        this.setState({
            picVisible: false,

        })
    }
    //保存新闻资讯
    saveNews() {
        let {
            noticeTitle,
            editorContent,
            typeId,
            NewsTitleImg,
            userId,
            userName,
            schoolId,
            schoolName,
            newsId,
            NewsID,
            imgUrl,
            newsAttachmentVoList
        } = this.state
        var $this = this;
        if (this.state.noticeTitle.length == 0 || this.state.noticeTitle.trim().length == 0) {
            message.error('新闻标题不能为空~');
            let count = 0;
            let timer = setInterval(() => {
                count++;
                setTimeout(() => {
                    if (count === 3) {
                        clearInterval(timer);
                    }

                    $('.notice-create-title').focus();
                }, 200);
                $('.notice-create-title').blur();
            }, 400);
            return;
        }
        if (this.state.typeId == '' || this.state.typeId == undefined) {
            message.error('新闻类型不能为空~');
            let count = 0;
            let timer = setInterval(() => {
                count++;
                setTimeout(() => {
                    if (count === 3) {
                        clearInterval(timer);
                        $('.div-select').css('border', 'solid 1px #bac7d9');
                        return;
                    }
                    $('.div-select').css('border', 'solid 2px #bac7d9');
                }, 200);
                $('.div-select').css('border', 'solid 2px #1890ff');

            }, 400);
            return;
        }
        if (this.state.editorContent && this.state.editorContent !== '<p><br></p>') {

        } else {
            message.error('新闻内容不能为空');
            return
        }

        postData('api/news/create/save', {
            newsTitle: noticeTitle,
            newsContent: editorContent,
            // newsCoverPath: NewsTitleImg.indexOf('http://') == -1 ? NewsTitleImg : NewsTitleImg.slice(sessionStorage.getItem('ResourceServerAddr').length, NewsTitleImg.length),
            newsCoverPath: imgUrl,
            userId: userId,
            userName: userName,
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            eduName: schoolName,
            newsTypeId: typeId,
            newsId: NewsID ? NewsID : newsId,
            newsAttachmentVoList: newsAttachmentVoList
        }).then((res) => {
            return res.json();
        }).then((json) => {

            if (json.code == 200) {
                $this.hideModal();
                message.success('保存新闻成功~', 3);
                $this.setState({
                    NoticeMain: 0,
                    editorContent: '',
                    clear: true,
                    typeId: undefined,
                    imgUrl: '',
                    newsAttachmentVoList: []
                }, () => { this.setState({ clear: false, typeId: undefined, imgUrl: '', newsAttachmentVoList: [] }) })
                this.props.reloadType();
                setTimeout(() => {
                    this.props.changeNoticeList(1);
                }, 300);
                $('#file').val('');
            } else {
                message.error(json.msg, 3);
            }
        })
    }
    hideModal() {
        this.props.hideModal();
        $('#file').val('');
        this.setState({
            visible: false,
            noticeTitle: '',
            fileList: [],
            imgList: [],
            newsAttachmentVoList: [],
            id: '',
            isupload: false,
            serverTime: '',
            NoticeContent: '',
            NoticeMain: 0,
            visible4: false,
            NewsID: '',
            loading: false,
            ImportClick: false,
            // isMouseOut: false,
            // isMouseOut1: false,
            // isMouseOut2: false,
            Newstype: { newsTypeName: '' },
            // NewsTypeList: [],
            NewsTypeListIDx: 0,
            editorContent: '',
            clear: true,
            typeId: undefined,
            imgUrl: '',
            imgCount: 0,
            fileCount: 0,
        }, () => { this.setState({ clear: false, typeId: undefined, imgUrl: '', newsAttachmentVoList: [], imgList: [], fileList: [], imgCount: 0, fileCount: 0, }) })
        // let ue = window.UE.getEditor('editor');
        // ue.ready(() => {
        //     ue.setContent('');
        // })

    }
    onChangePushFlag(e) {
        let {
            newsAttachmentVoList
        } = this.state
        if (newsAttachmentVoList.length > 1) {
            message.warn('发布至教育局附件不能超过一个！')
        }
        this.setState({
            pushFlag: newsAttachmentVoList.length > 1 ? false : e.target.value
        })
    }

    //类型管理相关方法
    changeAddKindTitle(e) {
        let value = e.target.value.replace(/\s/g, "");
        console.log(value);
        this.setState({ addTypeTitle: (value) })
        // setAddTypeTitle(value);
    }
    deleteType(data) {
        // console.log(data, 'data1');
        this.setState({
            alertInfo: {
                visible: true,
                // title: "确定要删除该类型吗？",
                title: "如该类型下有数据则会删除所有数据！",
                onCancel: () => {
                    this.setState({ alertInfo: {} });
                },
                onOk: () => {
                    delData('api/news/type/delete', {
                        typeId: data.newsTypeId
                    })
                        .then(res => res.json())
                        .then(result => {
                            if (result.code === "200") {
                                this.props.flashNews();
                                message.success("删除成功");
                                this.setState({ alertInfo: {} });
                                this.getTypeList();
                            }
                        });
                }
            }
        });
    };
    editType(targetIndex, type) {
        let list = JSON.parse(JSON.stringify(this.state.typeList));
        list.forEach((item, index) => {
            item.isEdit = false;
        });
        // console.log(list, 'list');
        if (type) {
            list.forEach((item, index) => {
                console.log(item);
                if (index === targetIndex) {
                    item.isEdit = true;
                    this.setState({ editTypeTitle: item.newTypeName })
                    // setEditTypeTitle(item.typeName);
                }
            });
        }
        this.setState({ typeList: list })
        // setTypeList(list);
    }
    //取消添加服务类型
    cancelAddType() {
        // setAddTypeTitle("");
        // setAddType(false);
        this.setState({ addTypeTitle: '', addType: false })
    }
    //操作服务类型
    operateType(data, type) {
        let {
            systemInfo
        } = this.state
        console.log(data, type, 'nihao11');

        if (type === "add") {
            if (this.state.addTypeTitle == '校园资讯' && systemInfo.beEdu == '1') {
                message.warn("该类型为局校互通类型，请更换名称！");
                return;
            }
            if (this.state.typeList.length > 19) {
                message.warn("最多只能添加20个类型");
                return;
            }
            if (!this.state.addTypeTitle) {
                message.warn("类型名称不能为空！");
                return;
            }
            postData('api/news/type/create', {
                // newsTypeId: "",
                newTypeName: this.state.addTypeTitle,
                eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            })
                .then(res => res.json())
                .then(data => {
                    if (data.code == 200) {
                        message.success("添加成功");
                        // this.props.getNewType();
                        this.cancelAddType();
                        this.getTypeList();
                    } else {
                        message.warn(data.msg)
                    }
                });
        }
        if (type === "edit") {
            if (this.state.editTypeTitle == '校园资讯' && systemInfo.beEdu == '1') {
                message.warn("该类型为局校互通类型，请更换名称！");
                return;
            }
            putData('api/news/type/update', {
                newsTypeId: data.newsTypeId,
                newTypeName: this.state.editTypeTitle,
                eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            })
                .then(res => res.json())
                .then(data => {
                    if (data.code == 200) {
                        message.success("编辑成功");
                        this.getTypeList();
                        // this.props.getNewType();
                    } else {
                        message.warn(data.msg)
                    }
                });
        }
        if (type === "delete") {
            let url = window.BasicProxy + "/api/collect/type/del?id=" + data.id;
            fetch
                .delete({ url })
                .then(res => res.json())
                .then(data => {
                    if (data.code == 200) {
                        message.success("删除成功");
                        this.getTypeList();
                    }
                });
        }
    }

    SelectOptionA = (item) => {
        console.log("选择的item:", item);
        this.setState({
            selectValue: item.newsTypeId == '' ? '' : item.text,
            typeId: item.newsTypeId,
        }, () => {
            if (item.newsTypeId == '') {
                this.setState({ typeVisible: true })
            }
        })
    }

    preViewFile = (item) => {
        let {
            schoolId,
            previewSystem,
        } = this.state
        let filePath = '';
        console.log(previewSystem)
        let eduId = JSON.parse(sessionStorage.getItem('userInfo')).eduId
        if (item.attachmentUrl.indexOf('http://') > -1 || item.attachmentUrl.indexOf('https://') > -1) {
            filePath = item.attachmentUrl;
        } else {
            filePath = sessionStorage.getItem('itemUrl') + '/' + item.attachmentUrl;
        }
        filePath = filePath.replace(/[\\]+/g, '/');
        let base64 = new Base64();
        let url = encodeURIComponent(base64.encode(filePath));
        let webSvrAddr = previewSystem[0].webSvrAddr;
        window.open(`${webSvrAddr}onlinePreview?url=${url}&eduId=${eduId}`);
    }
    downFile(url, name) {
        let data = this.state.data
        message.config({
            top: 50,
        })
        const hide = message.loading('正在下载，请稍等..', 0);
        var x = new XMLHttpRequest();
        // let url1 = sessionStorage.getItem('itemUrl') + url;
        console.log(url, 'url1');
        x.open("GET", url, true);
        x.responseType = 'blob';
        x.onload = function (e) {
            hide()
            var url = window.URL.createObjectURL(x.response);
            var a = document.createElement('a');
            a.href = url;
            a.download = name;
            a.click();
            URL.revokeObjectURL(url);
        }
        x.send();
    };
    //更换提示层——删除类型
    questionDelType = (data) => {
        let alert = lgAlert.show({
            duration: 0,
            content: <span>确定要删除<span className='high-light'>"{data.text}</span><span style={{ color: '#f06600' }}>"</span>类型吗？</span>,
            description: "谨慎操作，将同步删除该类型下的全部新闻资讯！",
            isShowCloseBtn: true,
            tipType: 'warning',
            tipMouldType: 'A',
            tipSize: 'big',
            confirmText: "确定删除",
            closeText: "再想想",
            showCover: true,
            coverZIndex: 1000,
            coverOpacity: 0.25,
            position: { xAxis: '50%', yAxis: '35%', showDirection: 'center', xOffset: '-50%' },
            onConfirm: () => {
                delData('api/news/type/delete', {
                    typeId: data.newsTypeId
                })
                    .then(res => res.json())
                    .then(result => {
                        if (result.code === "200") {
                            this.props.flashNews();
                            message.success("删除成功");
                            this.setState({ alertInfo: {} });
                            this.getTypeList();
                            // this.props.getNewType();
                        } else {
                            message.error("删除失败");
                        }
                    });
                lgAlert.close(alert.index)
            }
        });
    }
    render() {
        // console.log(this.props.NoticeMain)
        function showhtml(htmlString) {
            var html = { __html: htmlString };
            return <div className="Template-content" dangerouslySetInnerHTML={html}></div>;
        }
        // console.log(this.state.typeList[(this.state.typeList.findIndex(item => item.newsTypeId == this.state.typeId))], 'this.state.typeList[(this.state.typeList.findIndex(item=>item.typeId == this.state.typeId))].newTypeName');
        let {
            alertInfo,
            newsAttachmentVoList,
            noticeTitle,
            NewsTypeList,
            selectValue,
            systemInfo
        } = this.state
        return (
            <div className='notice-create'>
                {/* <Modal */}
                <LgPopLayer
                    className='notice-create-modal'
                    // style={{
                    //     backgroundColor: SKIN_BG_COLOR[sessionStorage.getItem('skin')]
                    // }}
                    title={this.props.NewsTitle}
                    visible={this.props.visible}
                    onOk={this.createNotice}
                    onCancel={this.hideModal}
                    okText="发布"
                    cancelText="取消"
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                    centered
                    width='1000px'
                    maskClosable={false}
                    isOpen={this.props.visible}//2023-07-17替换为公司组件
                    onIconClose={() => { this.hideModal() }}
                    height={740}
                    rootScroll={false}
                    // isShowBottom={false}
                    // footer={[<LgButton className='release_btn' backgroundType='opacification' type='info' key='test1' onClick={() => { this.createNotice() }}>发布</LgButton>,
                    // customOfBottom={
                    //     [
                    //         // <LgButton className='release_btn' backgroundType='opacification' type='info' key='test1' onClick={() => { this.createNotice() }}>发布</LgButton>,
                    //         // <LgButton className='cancel_btn' key='test' backgroundType='translucent' border type='info' onClick={() => { this.hideModal() }}>取消</LgButton>,
                    //         // <LgButton className='saveNews' key='test4' backgroundType='opacification' type='warning' onClick={() => { this.saveNews() }}>保存</LgButton>,
                    //         // <span className='notice-create-bottom3' key='test2' onClick={() => { this.onoK4() }}>预览</span>
                    //     ]
                    // }
                    customOfBottom={<div className='myBtn' style={{
                        backgroundColor: SKIN_BG_COLOR[sessionStorage.getItem('skin')]
                    }}>
                        <LgButton className='release_btn' backgroundType='opacification' type='info' key='test1' onClick={() => { this.createNotice() }}>发布</LgButton>
                        <LgButton className='cancel_btn' key='test' backgroundType='translucent' border type='info' onClick={() => { this.hideModal() }}>取消</LgButton>
                        <LgButton className='saveNews' key='test4' backgroundType='opacification' type='warning' onClick={() => { this.saveNews() }}>保存</LgButton>
                        <span className='notice-create-bottom3' key='test2' onClick={() => { this.onoK4() }}>预览</span>
                    </div>}

                // destroyOnClose={false}
                // wrapClassName='notice-create-Modal'
                >
                    <LgDrawer
                        cover
                        type={"right"}
                        style={{ position: "absolute" }}
                        zIndex={20000}
                        visible={this.state.typeVisible}
                        closeBtn={() => this.setState({ typeVisible: false })}
                        checkBtn={() => this.setState({ typeVisible: false })}
                        className="pop_seven"
                        width={650}
                        title={<>类型管理 <span className="type_title">- 最多支持添加20个类型</span></>}
                    >
                        {/* <p className="type_title">最多支持添加20个类型</p> */}
                        <div
                            className="kind_container"
                        >
                            {this.state.typeList.map((item, index) => {
                                if (item.isEdit) {
                                    console.log('edit1');
                                    return (
                                        <div
                                            className="add_kind_container"
                                            style={{ marginRight: 10 }}
                                            key={index}
                                        >
                                            <input
                                                type="text"
                                                value={this.state.editTypeTitle}
                                                maxLength={4}
                                                onChange={e =>
                                                    this.setState({ editTypeTitle: e.target.value.replace(/\s/g, "") })
                                                }
                                                autoFocus
                                            />
                                            <i
                                                className="oklogo"
                                                onClick={() => this.operateType(item, "edit")}
                                            ></i>
                                            <i
                                                className="nologo"
                                                onClick={() => this.editType(index)}
                                            ></i>
                                        </div>
                                    );
                                }
                                return (
                                    <div
                                        key={index}
                                        className="kind_one"
                                        onDoubleClick={() => this.editType(index, 1)}
                                    >
                                        <i
                                            className="closelogo"
                                            onClick={() => this.questionDelType(item)}
                                        ></i>
                                        {item.newTypeName}
                                    </div>
                                );
                            })}
                            {this.state.addType ? (
                                <div className="add_kind_container">
                                    <input
                                        type="text"
                                        value={this.state.addTypeTitle}
                                        maxLength={4}
                                        onChange={(e) => this.changeAddKindTitle(e)}
                                        autoFocus
                                    />
                                    <i
                                        className="oklogo"
                                        onClick={() => this.operateType("", "add")}
                                    ></i>
                                    <i className="nologo" onClick={() => this.cancelAddType()}></i>
                                </div>
                            ) : this.state.typeList.length >= 20 ? (
                                <div
                                    className="add_btn"
                                    style={{ cursor: "not-allowed", opacity: 0.5 }}
                                ></div>
                            ) : (
                                <div className="add_btn" onClick={() => { this.setState({ addType: true }) }}></div>
                            )}
                        </div>

                    </LgDrawer>
                    <ClassCropperModal
                        UpDataUrl={
                            sessionStorage.getItem('itemUrl') +
                            "SubjectRes_UploadHandler.ashx?method=doUpload_WholeFile&userid=" +
                            sessionStorage.getItem('UserID')
                        }
                        Visiable={this.state.picVisible}
                        InitPic={this.state.classResultImgUrl}
                        onClose={(NewsTitleImg) => { this.CropperModalClose(NewsTitleImg) }}
                        onSubmit={(file) => { this.handleGetResultImgUrl(file) }}
                        aspectRatio={this.state.aspectRatio}
                        baseUrl={sessionStorage.getItem('baseUrl')}
                    ></ClassCropperModal>
                    <div >
                        <label><span className="notice-create-span"><span className='must-fill'>*</span>标题:</span>
                            <LgInput input={{
                                value: this.state.noticeTitle,
                                autoFocus: true,
                                onInput: (e) => { this.changeNoticeTitle(e) },
                                placeholder: "请输入新闻标题",
                                maxLength: '30',
                            }}
                                value={this.state.noticeTitle}
                                className="news-title"
                                size='default'
                            />
                            {
                                noticeTitle.length > 0 ?
                                    <b className="notice-title-length" >{noticeTitle.length}/30</b>
                                    : ''
                            }
                        </label>
                        <div className="create-time-div" ><span className="notice-create-span"><span className='must-fill'>*</span>类型:</span>
                            <div className='div-select'>
                                <LgSelect className='select-type-create'
                                    datalist={NewsTypeList} SelectOption={this.SelectOptionA}
                                    placeholder='请选择' width={180}
                                    value={selectValue}
                                ></LgSelect>
                            </div >

                            <div className='news-title-div'> <i className='news-title-img' style={this.state.imgUrl ? { backgroundImage: 'url(' + this.state.imgUrl + ')' } : {}} onClick={(e) => {
                                this.setState({
                                    picVisible: true
                                })
                            }}>  </i> <div className='news-title-div1'>
                                    <b onClick={(e) => {
                                        this.setState({
                                            picVisible: true
                                        })
                                    }}>更换图片</b>
                                </div>
                            </div></div>


                        {/* <form id="uploadImg1">
                                <input name="file" type="file" id="file1" onChange={(e) => { this.formDataRemind(e, 1) }} />
                            </form> */}
                        {
                            systemInfo.beEdu == '1' ?
                                <div className='publish-edu'>
                                    <span style={{ marginRight: 5 }}>发布至教育局:</span>
                                    <div style={{ paddingTop: '3px' }}>
                                        <Radio.Group onChange={(e) => this.onChangePushFlag(e)} value={this.state.pushFlag}>
                                            <Radio value={true}>是</Radio>
                                            <Radio value={false}>否</Radio>
                                        </Radio.Group>
                                    </div>
                                    <span style={{ fontSize: '12px', color: '#999999' }}>(同步到教育局端的资讯无法撤回。)</span>
                                </div>
                                : ''
                        }
                        <span className="create-content"><span className='must-fill'>*</span>正文:</span><MyEditor id='editor' getHtmlContent={(html) => { this.setState({ editorContent: html && html !== '<p><br></p>' ? html : '' }, console.log(this.state.editorContent)) }} value={this.state.NoticeContent} clear={this.state.clear}  ></MyEditor>
                        <div className='upload-success-div'>
                            <span>  附件:</span> <span className='upload-span'>
                                <LgButton style={{ width: '80px', height: '30px', padding: '0 10px', marginRight: '10px' }} backgroundType='translucent' border type='info' onClick={() => { $('#file').click() }}>上传文件</LgButton>
                                {/* <b onClick={() => { $('#file').click() }}>上传文件</b>  */}
                                支持png/jpg/jpeg/pdf/doc/xls等格式且名称不能超过50字符文件 </span>
                            <form id="uploadImg" >
                                <input name="file" type="file" id="file" onChange={(e) => { this.formDataRemind(e) }} />
                            </form>

                            {this.state.isupload == 'true' ? <span className='upload-success-span upload-success-span1'>正在上传，请稍等~</span> : ''}
                        </div>
                        <div className='file-list'>
                            <Scrollbars autoHeight autoHeightMax={70} autoHide autoHideTimeout={100}>
                                {newsAttachmentVoList.length > 0 ? newsAttachmentVoList.map((item, index) => {
                                    return (
                                        <span className='upload-success-span'>
                                            <i className={item.attachmentName.slice(item.attachmentName.lastIndexOf('.') + 1, item.attachmentName.length)}></i>
                                            <b onClick={() => { this.preViewFile(item) }} style={{ cursor: 'pointer' }} title={item.attachmentName}>{item.attachmentName}</b><b>{item.attachmentSize / 1024 / 1024 > 1 ? '[' + (item.attachmentSize / 1024 / 1024).toFixed(2) + 'MB]' : '[' + (item.attachmentSize / 1024).toFixed(0) + 'KB]'}</b>
                                            <i className='file_del' onClick={() => { this.uploadDel(index, item) }}></i>
                                        </span>
                                    )
                                }) : ''}
                            </Scrollbars>
                        </div>
                        <Alert message={this.state.message} isOpen={this.state.isOpen} chooseFn={(data) => { this.DeleTypeFn(data) }}></Alert>
                    </div>
                    {/* </Scrollbars> */}
                </LgPopLayer>
                {/* </Modal> */}
                <Modal
                    className='Vews-news'
                    title="预览新闻"
                    visible={this.state.visible4}
                    // onOk={this.handleOk}
                    onCancel={this.handleCancel4}
                    footer={null}
                    width='1260px'
                    centered
                // destroyOnClose={true}
                >
                    <Scrollbars style={{ width: 1260, height: 620 }}>
                        <div style={{ padding: '24px' }}>
                            <h1 style={{ textAlign: 'center', fontSize: '30px', color: '#333' }}>{this.state.noticeTitle.length > 0 ? this.state.noticeTitle : '您还没有输入新闻标题哦~'}</h1>
                            <p className='notice-details-message'><span> <b>发布时间: </b>{this.state.serverTime}</span><span><b> 类别: </b> {this.state.typeList[(this.state.typeList.findIndex(item => item.newsTypeId == this.state.typeId))]?.newTypeName}</span><span><b> 阅读次数:  </b> 0次</span></p>
                            <p className='notice-details-border'></p>
                            {/* <div> <i className='news-title-img news-title-img1' style={this.state.NewsTitleImg.length>0?{backgroundImage:'url('+sessionStorage.getItem('ResourceServerAddr')+'/'+this.state.NewsTitleImg+')'}:{}}>  </i> </div> */}
                            <div className='notice-contect'> {this.state.visible4 ? showhtml(this.state.editorContent) : ''}</div>
                            {newsAttachmentVoList.length > 0 ? <div className="notice-down-box" style={{ height: newsAttachmentVoList.length > 1 ? '220px' : '' }}>
                                <p><i ></i>附件下载</p>
                                <Scrollbars autoHeight autoHeightMax={180} autoHide autoHideTimeout={100}>
                                    {
                                        newsAttachmentVoList.map(item => {
                                            return (
                                                <div className="notice-down-message">
                                                    <span className={item.attachmentName.slice(item.attachmentName.lastIndexOf('.') + 1, item.attachmentName.length) + ' uploadType-img'}></span>
                                                    <p onClick={() => this.preViewFile(item)} style={{ cursor: 'pointer' }} title={item.attachmentName.length > 60 ? item.attachmentName : ''}>{item.attachmentName.length > 60 ? item.attachmentName.slice(0, 58) + '..' : item.attachmentName}
                                                        <span>{(item.attachmentSize / 1024 / 1024) >= 1 ? '[' + (item.attachmentSize / 1024 / 1024).toFixed(1) + 'MB]' : '[' + (item.attachmentSize / 1024).toFixed(1) + 'KB]'}</span></p>
                                                    <LgButton onClick={() => { this.preViewFile(item) }} textUnderline type='info' shapeType='text' className='preview-file'>预览</LgButton>
                                                    <b className='down-file' href={item.attachmentUrl.indexOf('.mp4') === -1 && item.attachmentUrl.indexOf('.mp4') === -1 ? item.attachmentUrl : item.attachmentUrl + '?filename=' + item.attachmentName.slice(0, -4)} download={item.attachmentName} onClick={() => { this.downFile(item.attachmentUrl, item.attachmentName); }}>下载</b>
                                                </div>
                                            )
                                        })
                                    }
                                </Scrollbars>
                            </div>
                                : ''}

                        </div>  </Scrollbars>
                </Modal>
                {/* 类型管理 */}
                <Modal
                    width={696}
                    height={322}
                    className="type_modal"
                    title="类型管理"
                    // visible={this.state.typeVisible}
                    noFooter={true}
                    footer={[]}
                    changeVisible={value => modalChange("type", value)}
                    // onOk={() => this.setState({ typeVisible: false })}
                    onCancel={() => this.setState({ typeVisible: false })}
                >
                    <p className="type_title">最多支持添加20个类型</p>
                    <Scrollbars autoHeight autoHeightMax={290}>
                        <div
                            className="kind_container"
                        >
                            {this.state.typeList.map((item, index) => {
                                if (item.isEdit) {
                                    console.log('edit1');
                                    return (
                                        <div
                                            className="add_kind_container"
                                            style={{ marginRight: 10 }}
                                            key={index}
                                        >
                                            <input
                                                type="text"
                                                value={this.state.editTypeTitle}
                                                maxLength={4}
                                                onChange={e =>
                                                    this.setState({ editTypeTitle: e.target.value.replace(/\s/g, "") })
                                                }
                                                autoFocus
                                            />
                                            <i
                                                className="oklogo"
                                                onClick={() => this.operateType(item, "edit")}
                                            ></i>
                                            <i
                                                className="nologo"
                                                onClick={() => this.editType(index)}
                                            ></i>
                                        </div>
                                    );
                                }
                                return (
                                    <div
                                        key={index}
                                        className="kind_one"
                                        onDoubleClick={() => this.editType(index, 1)}
                                    >
                                        <i
                                            className="closelogo"
                                            onClick={() => this.deleteType(item)}
                                        ></i>
                                        {item.newTypeName}
                                    </div>
                                );
                            })}
                            {this.state.addType ? (
                                <div className="add_kind_container">
                                    <input
                                        type="text"
                                        value={this.state.addTypeTitle}
                                        maxLength={4}
                                        onChange={(e) => this.changeAddKindTitle(e)}
                                        autoFocus
                                    />
                                    <i
                                        className="oklogo"
                                        onClick={() => this.operateType("", "add")}
                                    ></i>
                                    <i className="nologo" onClick={() => this.cancelAddType()}></i>
                                </div>
                            ) : this.state.typeList.length >= 20 ? (
                                <div
                                    className="add_btn"
                                    style={{ cursor: "not-allowed", opacity: 0.5 }}
                                ></div>
                            ) : (
                                <div className="add_btn" onClick={() => { this.setState({ addType: true }) }}></div>
                            )}
                        </div>
                    </Scrollbars>
                </Modal>
                <Modal
                    className='add-news-type'
                    visible={alertInfo.visible}
                    onOk={alertInfo.onOk}
                    onCancel={alertInfo.onCancel}
                    okText="确定"
                    cancelText="取消"
                    centered
                    footer={null}
                    width='400px'
                    height='300px'
                >
                    <div className="border alert_dialog_wrapper" id="alert_dialog_wrapper" >
                        <div className="alert_dialog_content ">
                            <div className="alert_dialog_logo"></div>
                            <div className="alert_dialog_msg btn-query">{alertInfo.title}</div>
                        </div>
                        <div className="alert_dialog_footer">
                            <LgButton className='operation-btn' backgroundType='opacification' gradient radius type='info' onClick={() => { alertInfo.onOk() }}>确定</LgButton>
                            <LgButton className='operation-btn' radius backgroundType='transparent' border type='info' onClick={() => { alertInfo.onCancel() }}>取消</LgButton>
                        </div>
                    </div>
                    {/* </div> */}
                </Modal>
                {this.state.loading ? <Spin size="large" /> : ''}
            </div>
        )
    }
}

export default CreateNotice;